package com.purong.purong.activity;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.purong.purong.Contant;
import com.purong.purong.R;
import com.purong.purong.bean.BankLoanDetBean;
import com.purong.purong.bean.BankLoanApplyBean;
import com.purong.purong.bean.LoginBean;
import com.purong.purong.bean.ProtocolBean;
import com.purong.purong.util.CommonUtil;
import com.purong.purong.util.SharePreUtil;
import com.purong.purong.widget.LoadingDialog;
import com.yao.sdk.net.ResponseInfo;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import cn.jpush.android.api.JPushInterface;

/**
 * Created by zengwenjie on 2017/11/30.
 */
public class BankLoanMaterOneActivity extends BaseActivity {
    private EditText verEd,phoneEd;
    private TextView getCode;
    private ImageView checkImg;
    private boolean isCheck=true;
    private boolean canGetValid=true;
    private int timeCount=-1;
    private BankLoanDetBean detBean;
    private String money,period;
    private LoadingDialog mDialog;
    @Override
    public int getRootViewId() {
        return R.layout.activity_apply_material_one;
    }

    @Override
    public void initBundle() {
        detBean=(BankLoanDetBean)getIntent().getSerializableExtra("BANK_LOAN");
        money=getIntent().getStringExtra("MONEY");
        period=getIntent().getStringExtra("PERIOD");
    }

    @Override
    public void initView() {
        mDialog=new LoadingDialog(this);
        checkImg=(ImageView)findViewById(R.id.check_img);
        verEd=(EditText)findViewById(R.id.verification_ed);
        phoneEd=(EditText)findViewById(R.id.phone_ed);
        getCode=(TextView)findViewById(R.id.get_code);
    }

    @Override
    public void initData() {

    }
    private void apply(){
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("loan_id",detBean.getLoan_product_id());
        params.put("province_id", SharePreUtil.getInstance(this).getLoactionParentId());
        params.put("city_id",SharePreUtil.getInstance(this).getLoactionAreaId());
        params.put("apply_money",money);
        params.put("apply_period",period);
        if (!request(Contant.LOAN_APPLY, params, true, true)){
            if (mDialog.isShowing())
                mDialog.dismiss();
        }
    }
    private void getProtocol(){
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("protocol_code","LoanProtocol");
        request(Contant.PROTOCOL, params, true,true);
    }
    private void getCode(String phone){
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("phone",phone);
        canGetValid=!request(Contant.SMS, params, true,true);
    }
    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what==-1){
                getCode.setTextColor(getResources().getColor(R.color.blue));
                getCode.setText("获取验证码");
                canGetValid=true;
            }else {
                getCode.setText("重新获取"+"("+msg.what+")秒");
            }
        }
    };
    public void countDown(){
        timeCount=60;
        getCode.setTextColor(getResources().getColor(R.color.text_gray));
        Timer timer=new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                timeCount--;
                handler.sendEmptyMessage(timeCount);
                if (timeCount==-1){
                    this.cancel();
                }
            }
        },0,1000);
    }
    private void smsLogin(String phone,String verification){
        mDialog.show();
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("user_phone",phone);
        params.put("user_verification",verification);
       if (!request(Contant.SMS_LOGIN, params, true,false)){
           mDialog.dismiss();
       }
    }
    @Override
    public void onResponse(ResponseInfo responseInfo) {
        if (hasDestroy())
            return;
        super.onResponse(responseInfo);
        if (responseInfo.url.equals(Contant.SMS)){
            if (responseInfo.isRequestOk){
                showToast("验证码已发送");
                countDown();
            }else {
                canGetValid=true;
            }
        }else if (responseInfo.url.equals(Contant.SMS_LOGIN)){
            if (responseInfo.isRequestOk){
                try{
                    LoginBean loginBean= JSON.parseObject(responseInfo.content,LoginBean.class);
                    loginBean.setPwd("");
                    loginBean.save(this);
                    JPushInterface.setAlias(this,0,loginBean.getUser_id());
                    apply();

                }catch (Exception e){

                }
            }else {
                if (mDialog.isShowing())
                mDialog.dismiss();
            }

        }else if (responseInfo.url.equals(Contant.PROTOCOL)){
            if (responseInfo.isRequestOk){
                try {
                    ProtocolBean bean= JSON.parseObject(responseInfo.content,ProtocolBean.class);
                    if (bean!=null&&bean.getUrl()!=null){
                        Intent intent=new Intent(this,WebActivity.class);
                        intent.putExtra("TITLE", "普融服务协议");
                        intent.putExtra("URL", bean.getUrl());
                        intent.putExtra("TITLEBAR", true);
                        startActivity(intent);
                    }

                }catch (Exception e){

                }
            }
        }else if (responseInfo.url.equals(Contant.LOAN_APPLY)){
            if (mDialog.isShowing())
            mDialog.dismiss();
            if (responseInfo.isRequestOk){
                try{
                    BankLoanApplyBean bean=JSON.parseObject(responseInfo.content,BankLoanApplyBean.class);
                    Intent intent=new Intent(this,BankLoanMaterTwoActivity.class);
                    intent.putExtra("BANK_LOAN",detBean);
                    intent.putExtra("APPLY_MONEY",responseInfo.params.get("apply_money"));
                    intent.putExtra("APPLY_PERIOD",responseInfo.params.get("apply_period"));
                    intent.putExtra("FIRST_STEPS",true);
                    if (bean!=null&&bean.getLoan_apply_id()!=null){
                        intent.putExtra("APPLY_ID",bean.getLoan_apply_id());
                    }
                    startActivity(intent);
                    this.finish();
                }catch (Exception e){

                }
            }
        }
    }

    public void onClick(View v){
        switch (v.getId()){
            case R.id.protocol:
                getProtocol();

                break;
            case R.id.check_img:
                if (!isCheck){
                    checkImg.setImageResource(R.drawable.icon_checkbox_sel);
                    isCheck=true;
                }else {
                    checkImg.setImageResource(R.drawable.icon_checkbox_nor);
                    isCheck=false;
                }
                break;
            case R.id.next:
                if (phoneEd.getText().toString().trim().equals("")) {
                    showToast("请输入手机号");
                    return;
                }
                if (verEd.getText().toString().trim().equals("")){
                    showToast("请输入验证码");
                    return;
                }
                if (!isCheck){
                    showToast("未同意普融服务协议");
                    return;
                }
                if (detBean==null||money==null)
                    return;
                smsLogin(phoneEd.getText().toString().trim(),verEd.getText().toString().trim());
                break;
            case R.id.get_code:
                if (!canGetValid)
                    return;
                if (phoneEd.getText().toString().trim().equals("")) {
                    showToast("请输入手机号");
                    return;
                }
                if (!CommonUtil.isPhoneNum(phoneEd.getText().toString().trim())) {
                    showToast("请输入正确的手机号");
                    return;
                }
                getCode(phoneEd.getText().toString());
                break;
            case R.id.left_back:
                this.finish();
                break;
        }
    }
}
